<?php
    
    class RegisterHandler{
    	
		private $m_LoginHandler = NULL;
		private $m_DBConnection = NULL;
		private $m_usersTableName = "users";
		
		public function __construct(LoginHandler $aLoginHandler, DBConnection $aDBConnection){
			$this->m_LoginHandler = $aLoginHandler;
			$this->m_DBConnection = $aDBConnection;
		}
		
		//Function to Add a new User to the Database
		public function AddUser($username,$password)
		{
			if($this->m_LoginHandler->CheckIfUserExists($username) == true){
				return false;
			}
			
			if(Validate::ValidatePassword($password) == false){
				return false;
			}
			
			if ($username != Validate::StripAll($username)){
				return false;
			}
			
			if(strlen($username) == 0){
				return false;
			}
			
			$salt = $this->m_LoginHandler->GenerateRandomSalt();
			$password = $this->m_LoginHandler->HashPassword($password, $salt);
			
			$sql = "INSERT INTO $this->m_usersTableName VALUES(?, '$password', '$salt', '')";
	                
	        $aStatement = $this->m_DBConnection->Prepare($sql);
			
	      	$aStatement->bind_param("s", $username);
				
			$aStatement->execute();
			
			$temppassword = $this->m_LoginHandler->GenerateTempPassword($username);
			return true;
		}
		
		//Function to remove a user from the Database
		public function RemoveUser($username){
			
			if($this->m_LoginHandler->CheckIfUserExists($username) == false){
				return false;
			}
			$sql = "DELETE FROM $this->m_usersTableName WHERE Username = ?";
	                
	        $aStatement = $this->m_DBConnection->Prepare($sql);
			
	      	$aStatement->bind_param("s", $username);
				
			$aStatement->execute();
			
			return true;
		}
		
		public function Test(){
			$this->RemoveUser("testUser42");
			$this->RemoveUser("AGoodUsername");
			$this->RemoveUser("");
			
			$this->AddUser("testUser42","testPassword42");
			if($this->m_LoginHandler->CheckIfUserExists("testUser42") == false){
				Log::LogMessage("AddUser is not working as intended");
				return false;
			}
			if($this->AddUser("","testPassword42") == true){
				Log::LogMessage("AddUser is not working as intended");
				return false;
			}
			if($this->AddUser("AGoodUsername","short") == true){
				Log::LogMessage("AddUser is not working as intended");
				return false;
			}
			if($this->AddUser("<a href='Something'>blabla</a>","short") == true){
				Log::LogMessage("AddUser is not working as intended");
				return false;
			}
			$this->RemoveUser("testUser42");
			if($this->m_LoginHandler->CheckIfUserExists("testUser42") == true){
				Log::LogMessage("RemoveUser is not working as intended");
				return false;
			}
			return true;
			
		}
    }
